from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import os
import logging
from config import config
from utils.session_manager import SessionManager
from utils.image_processor import ImageProcessor
from utils.gemini_client import GeminiClient
from utils.error_handler import setup_error_handlers
from utils.rate_limiter import RateLimiter

def create_app(config_name=None):
    """创建Flask应用实例"""
    app = Flask(__name__)
    
    # 加载配置
    config_name = config_name or os.environ.get('FLASK_ENV', 'default')
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    
    # 初始化CORS
    CORS(app, origins=app.config['CORS_ORIGINS'])
    
    # 设置日志
    if not app.debug:
        logging.basicConfig(level=logging.INFO)
    
    # 初始化组件
    session_manager = SessionManager(app.config['REDIS_URL'], app.config['SESSION_TIMEOUT'])
    image_processor = ImageProcessor(app.config['UPLOAD_FOLDER'], app.config['ALLOWED_EXTENSIONS'])
    gemini_client = GeminiClient(app.config['GEMINI_API_KEY'], app.config['GEMINI_MODEL'])
    rate_limiter = RateLimiter(app.config['API_RATE_LIMIT'])
    
    # 注册错误处理器
    setup_error_handlers(app)
    
    # 注册蓝图
    from routes.api import create_api_blueprint
    api_bp = create_api_blueprint(session_manager, image_processor, gemini_client, rate_limiter)
    app.register_blueprint(api_bp, url_prefix='/api/v1')
    
    # 健康检查端点
    @app.route('/health')
    def health_check():
        return jsonify({
            'status': 'healthy',
            'service': 'image-generation-proxy',
            'version': '1.0.0'
        })
    
    # 根路径
    @app.route('/')
    def index():
        return jsonify({
            'message': '图生图转接API服务',
            'version': '1.0.0',
            'endpoints': {
                'health': '/health',
                'api_docs': '/api/v1/docs',
                'generate': '/api/v1/generate',
                'session': '/api/v1/session'
            }
        })
    
    return app

if __name__ == '__main__':
    app = create_app()
    app.run(host='0.0.0.0', port=5000, debug=True)
